package com.blog.blog.config;

import com.blog.blog.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AdminAuthInterceptor implements HandlerInterceptor {

    private final AuthService authService;

    public AdminAuthInterceptor(AuthService authService) {
        this.authService = authService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String method = request.getMethod();

        boolean isWriteArticle = uri.startsWith("/api/articles") && !HttpMethod.GET.matches(method);
        boolean isAdminApi = uri.startsWith("/api/admin");
        boolean isWriteResume = uri.startsWith("/api/resume") && !HttpMethod.GET.matches(method);
        boolean isResumeMe = "/api/resume/me".equals(uri);

        if (!(isWriteArticle || isAdminApi || isWriteResume || isResumeMe)) {
            return true;
        }

        String auth = request.getHeader("Authorization");
        if (auth == null || !auth.startsWith("Bearer ")) {
            unauthorized(response);
            return false;
        }
        String token = auth.substring(7);
        Long userId = authService.verify(token);
        if (userId == null) {
            unauthorized(response);
            return false;
        }
        request.setAttribute("X-User-Id", userId);
        return true;
    }

    private void unauthorized(HttpServletResponse response) throws Exception {
        response.setStatus(401);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"未授权\"}");
    }
}


